package com.woniuxy.crm.type;

import com.woniuxy.crm.annotation.EnumValue;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.woniuxy.crm.Menus.ManagerMenum;

import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class CrmEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    private final Class<E> type;
    private Field field;

    public CrmEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;

        Field[] fields = type.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(EnumValue.class)) {
                this.field = field;
                break;
            }
        }
        this.field.setAccessible(true);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        try {
            Object o = field.get(parameter);
            if (jdbcType == null) {
                ps.setString(i, o.toString());
            } else {
                ps.setObject(i, o.toString(), jdbcType.TYPE_CODE);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
        return getInstance(s);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return getInstance(s);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return getInstance(s);
    }

    private E getInstance(String s) {
        for (E constant : type.getEnumConstants()) {
            try {
                if (field.get(constant).toString().equals(s)) {
                    return constant;
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}

